/*
 * ViewTicketCommand.java
 *
 * Created on October 4, 2007, 4:09 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package drb;

import java.io.BufferedReader;
import java.sql.*;
import java.util.ArrayList;

/**
 *
 * @author Asger
 */
public class ViewTicketCommand extends PromptingCommand {
    
    public Passenger passenger;
    
    /** Creates a new instance of ViewTicketCommand */
    public ViewTicketCommand(BufferedReader input) {
        super(input);
    }
    
    public void execute() throws SQLException {        
        // Get the list of tickets that are not yet expired
        ArrayList<Ticket> tickets = getUnexpiredTicketsByOwner(passenger);
        
        int numTickets = tickets.size();
        
        System.out.println("-------------------------------");
        if (numTickets == 0)
            System.out.println("You do not appear to own any active tickets.");
        else
            System.out.println("You have " + numTickets + " active tickets.");
        System.out.println("-------------------------------");
        
        // Print the tickets
        for (Ticket ticket : tickets) {
            ticket.printDetails();
            ticket.printTransfers();
            ticket.printReservations(connection);
            System.out.println("-------------------------------");
        }
    }
    
    
    
    public ArrayList<Ticket> getUnexpiredTicketsByOwner(Passenger owner) throws SQLException {
        
        String sql = "SELECT * FROM tickets t WHERE t.passenger_cpr="+owner.cpr+" AND " +
                "EXISTS (SELECT * FROM ticketdue td NATURAL JOIN connections c WHERE td.ticket_id=t.ticket_id AND c.arrival>="+getTimeNow()+")";
        ResultSet result = connection.createStatement().executeQuery(sql);
        ArrayList<Ticket> tickets = new ArrayList<Ticket>();
        
        // Get all the tickets.
        while (result.next()) {
            Ticket ticket = Ticket.parse(result);
            ticket.passenger = owner;
            ticket.fetchTrainRoute(connection);
            tickets.add(ticket);
        }
        
        return tickets;
    }
}





















